package com.diannuo.springboot.controller;

import com.alibaba.fastjson.JSON;
import com.diannuo.springboot.dao.UserMapper;
import com.diannuo.springboot.model.User;
import com.diannuo.springboot.model.UserVO;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class HelloWorldController {

	@Resource
	UserMapper userMapper;
//	@Resource
//	Util util;
	/**
	 * hello
	 * @param user
	 * @param result
	 * @return
	 */
	@PostMapping("/hello")
	public String hello(@RequestBody @Validated UserVO user, BindingResult result){
		if (result.hasErrors()){
			StringBuilder sb=new StringBuilder();
			List<FieldError> fieldErrors = result.getFieldErrors();
			fieldErrors.forEach(fieldError -> {
				sb.append(fieldError.getField()+":"+fieldError.getDefaultMessage()+"\n");
			});
			return sb.toString();
		}
		return JSON.toJSONString(user);
	}

	/**
	 * hello1
	 * @param user
	 * @return
	 */
	@PostMapping(value = "hello1",consumes = "application/json",produces = "application/json")
	public User hello1(@RequestBody User user){
//		List<User> list=new ArrayList<>();
//		user.setId(30);
//		list.add(user);
//		User user1=new User();
//		user1.setUsername(user.getUsername()+"asdsa");
//		user1.setPassword(user.getPassword());
//		user1.setCreateTime(LocalDateTime.now());
//		user1.setId(31);
//		list.add(user1);
//		int i = userMapper.insertList(list);
//		System.out.println(i);
		int i = userMapper.insertTest(user);
		System.out.println(i);
		return user;
	}

	/**
	 * hello2
	 * @param user
	 * @return
	 */
	@PostMapping(value = "hello2")
	public User hello2(@RequestBody User user){
		System.out.println(user.getCreateTime());
		System.out.println(user.getToday());
		System.out.println(user.getTimer());
		return user;
	}

	/**
	 * hello3
	 * @return
	 */
	@PostMapping(value = "hello3",produces = "application/json")
	public String hello3(@RequestBody @Validated UserVO user){
		System.out.println(111);
		Map<String,String> map=new HashMap<>();
		map.put("sss","asdas");
		return "map";
	}
	/**
	 * hello4
	 * @return
	 */
	@PostMapping(value = "hello4")
	public String hello4(){
		System.out.println(111);
		Map<String,String> map=new HashMap<>();
		map.put("sss","asdas");
		return "map";
	}
}
